package com.atguigu.datastream.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;




/**
 * ClassName: Flink02_Stream_WordCount_Bounded
 * Package: com.atguigu.day01
 * Description:
 *
 * @Author ChenJun
 * @Create 2023/4/6 18:13
 * @Version 1.0
 */
public class Flink02_Stream_WordCount_Bounded {
    public static void main(String[] args) throws Exception {
        //1. 创建Flink流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //将并行度设置为1
        env.setParallelism(1);

        //2.读取文件  有界数据
        DataStreamSource<String> wordDStream = env.readTextFile("input/word.txt");

        //3.通过flatmap将单词打散
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordToOneDStream = wordDStream.flatMap(new FlatMapFunction<String,
                Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] words = s.split(" ");
                for (String word : words) {
                    collector.collect(new Tuple2<>(word, 1));
                }
            }
        });

        //4.通过keyBy进行分组
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = wordToOneDStream.keyBy(new KeySelector<Tuple2<String, Integer>, String>() {
            /**
             *
             * @param value 流中的数据
             * @return
             * @throws Exception
             */
            @Override
            public String getKey(Tuple2<String, Integer> value) throws Exception {
                return value.f0;
            }
        });

        // 5.计算
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = keyedStream.sum("f1");

        //6.打印
        result.print();

        //7 .执行
        env.execute();


    }
}
